package com.lagou.edu.wwyan.nacos.code.service.impl;

import com.lagou.edu.wwyan.nacos.code.dao.LagouAuthCodeDao;
import com.lagou.edu.wwyan.nacos.code.entity.LagouAuthCode;
import com.lagou.edu.wwyan.nacos.code.service.LagouAuthCodeService;
import com.lagou.edu.wwyan.nacos.email.service.LagouEmailService;
import com.lagou.edu.wwyan.nacos.user.service.LagouUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

//@Service
@DubboService
@Slf4j
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {
    private Random random = new Random();
//    @Autowired
    @DubboReference(retries = 0,timeout = 3000)
    private LagouEmailService emailService;
//    @Autowired
    @DubboReference(retries = 0,timeout = 3000)
    private LagouUserService lagouUserService;
    @Autowired
    private LagouAuthCodeDao authCodeDao;
    private static final int EXPIRE_TIME_MINUTES = 10;
    @Override
    public Boolean createAndSend(String email) {
        Boolean register = lagouUserService.isRegister(email);
        if (register != null && register){
            return false;
        }
        String code = createCode();
        //发送验证码
        Boolean aBoolean = emailService.sendCode(email, code);
        if (aBoolean == null || !aBoolean){
            return false;
        }

        LagouAuthCode authCode = new LagouAuthCode();

        authCode.setEmail(email);
        authCode.setCode(code);
        LocalDateTime now = LocalDateTime.now();
        authCode.setCreatetime(now);
        //10分钟内有效
        authCode.setExpiretime(now.plusMinutes(EXPIRE_TIME_MINUTES));
        this.authCodeDao.save(authCode);

        return true;
    }

    private String createCode() {
        int code =   random.nextInt(1000000);
        return String.format("%06d", code);
    }

    @Override
    public Integer validate(String email, String code) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = now.minusMinutes(EXPIRE_TIME_MINUTES);
        //按照失效时间倒叙
        PageRequest pageable = PageRequest.of(0, 1, Sort.Direction.DESC,"expiretime");
        List<LagouAuthCode> codes = authCodeDao.getByEmailAndCode(pageable,email, code);
        if (codes.isEmpty()){
            //错误
            return 1;
        }
        LagouAuthCode authCode = codes.get(0);
        LocalDateTime expiretime = authCode.getExpiretime();
        if (expiretime == null || time.isAfter(expiretime)){
            //超时
            return 2;
        }
        return 0;
    }
}
